import { Injectable, NgZone } from '@angular/core'
import { BehaviorSubject, Observable, Subject } from 'rxjs'
import { IpcRenderer } from 'electron'
import { CHANNEL } from '../../../src_main/channels'

const electron = window.require('electron')

const ipcRenderer: IpcRenderer = electron.ipcRenderer

@Injectable({
  providedIn: 'root'
})
export class IpcService {
  public reply$: Observable<any>

  constructor(zone: NgZone) {
    const reply$ = new BehaviorSubject<any>([])
    this.reply$ = reply$.asObservable()

    ipcRenderer.on(CHANNEL, (event, ...args) => {
      console.log(args)
      zone.run(() => reply$.next(args))
    })
  }

  public send(...args): void {
    console.log('send', args)
    ipcRenderer.send(CHANNEL, ...args)
  }
}
